package com.neusoft.resturant.controller;

import com.alibaba.fastjson2.JSON;
import com.neusoft.resturant.common.utils.R;
import com.neusoft.resturant.entity.ResShop;
import com.neusoft.resturant.service.IResShopService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/api/redis")
public class RedisController {
    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private IResShopService shopService;
    @GetMapping("/put")
    public R put(String key, String value) {
        // 存入，设置key,value,存入时间，时间单位
        redisTemplate.opsForValue().set(key, value, 1, TimeUnit.HOURS);
        // 取出
        String v = (String) redisTemplate.opsForValue().get(key);
        Map<String, Object> result = new HashMap<>();
        result.put("key", key);
        result.put("value", v);
        return R.success(result);
    }

    /**
     * 传入id,查询店铺信息，将店铺信息放入缓存
     * @param id
     * @return
     */
    @GetMapping("/putObj")
    public R putObj(@RequestParam Long id) {
        ResShop resShop = shopService.selectResShopById(id);
        String jsonStr = JSON.toJSONString(resShop);
        redisTemplate.opsForValue().set(String.valueOf(resShop.getId()), jsonStr, 1, TimeUnit.HOURS);
        String v = (String)redisTemplate.opsForValue().get(String.valueOf(id));
        resShop = JSON.parseObject(v,ResShop.class);
        return R.success(resShop);
    }

    /**
     * 传入店铺id,从缓存中获取店铺信息
     * @param id
     * @return
     */
    @GetMapping("/getObj")
    public R getObj(@RequestParam Long id) {
        String v = (String) redisTemplate.opsForValue().get(String.valueOf(id));
        System.out.println(v);
        ResShop resShop = JSON.parseObject(v, ResShop.class);
        return R.success(resShop);
    }
}
